package com.shiro.util;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.StringTokenizer;

/**
 * Created with IntelliJ IDEA.
 * User: dengpeng
 * Date: 2018/6/29
 * Time: 16:47
 * Description: map与String转换
 */
public class MapUtil {

    /**
     * Description: map转String
     *
     * @param map map
     * @return {@link String}
     */
    public static String transMapToString(Map map) {

        StringBuilder builder = new StringBuilder();
        for (Iterator iterator = map.entrySet().iterator(); iterator.hasNext(); ) {
            Map.Entry entity = (Map.Entry) iterator.next();
            builder.append(entity.getKey().toString()).append("'")
                   .append(null == entity.getValue() ? "" : entity.getValue().toString())
                   .append(iterator.hasNext() ? "^" : "");
        }
        return builder.toString();
    }

    @SuppressWarnings("unchecked")
    public static Map transStringToMap(String mapString) {

        Map map = new HashMap();
        StringTokenizer items;
        for (StringTokenizer entrys = new StringTokenizer(mapString, "^"); entrys.hasMoreTokens(); map
                        .put(items.nextToken(), items.hasMoreTokens() ? ((Object) (items.nextToken())) : null))
            items = new StringTokenizer(entrys.nextToken(), "'");
        return map;
    }
}
